public class HashBucket {
    private class Node {
        private int key;
        private int value;
        Node next;


        public Node(int key, int value) {
            this.key = key;
            this.value = value;
        }
    }


    private Node[]  array;
    private int size;   // 当前的数据个数
    private static final double LOAD_FACTOR = 0.75;
    private static final int DEFAULT_SIZE = 8;//默认桶的大小

    public int put(int key, int value) {
        //计算索引位置
        int index = key % size;

        Node cur = array[index];
        if(cur == null){
            array[index] = new Node(key, value);
            return -1;
        }

        while(cur.next != null){
            if(cur.next.key == key){
                int tmp = cur.next.value;
                cur.next.value = value;
                return tmp;
            }
            cur = cur.next;
        }

        //尾插法
        cur.next = new Node(key,value);
        size++;


        if(loadFactor() >= LOAD_FACTOR){
            resize();
        }

        return -1;
    }


    private void resize() {
        Node[] newArray = new Node[array.length * 2];
        for(int i = 0; i < array.length; i++){
            Node cur = array[i];
            while(cur != null){
                Node next = cur.next;
                int index = cur.key % newArray.length;
                cur.next = newArray[index];
                newArray[index] = cur;
                cur = next;
            }
        }
        array = newArray;
    }


    private double loadFactor() {
        return size * 1.0 / array.length;
    }


    public HashBucket() {
        array = new Node[DEFAULT_SIZE];
    }


    public int get(int key) {
        int index = key % array.length;
        Node cur =  array[index];
        while(cur != null){
            if(cur.key == key){
                return cur.value;
            }
            cur = cur.next;
        }
        return  -1;
    }
}
